#include <stdlib.h>
#include <sys/mman.h>
#include "funcontainer.h"

int FunConAdd(void * pfun,FUNCON_S * pbak,void * ptofun)
{
	int ret;
	int len;
	FUNCON_S * p;
	
	if( NULL == pfun || NULL == pbak || NULL == ptofun )
	{
		return -1;
	}
	
	len = ptofun - pfun - 5;
	p = (void *)pfun;
	
	ret = mprotect((void *)((unsigned int)p&~(0x1000-1)),1,PROT_WRITE |  PROT_READ | PROT_EXEC );
	if( ret )
	{
		return ret;
	}
	
	*pbak = *p;
	
    p->jmp_t = 0xe9;
    p->addr = len;
	
	ret = mprotect((void *)((unsigned int)p&~(0x1000-1)),1, PROT_READ | PROT_EXEC );
	if( ret )
	{
		return ret;
	}
	
	return 0;
}

int FunConRemove(void *pfun,FUNCON_S * pbak,void *ptofun)
{
	int ret;
	FUNCON_S * p;
	
	if( NULL == pfun || NULL == pbak || NULL == ptofun )
	{
		return -1;
	}
	
	p = (void *)pfun;
	
	ret = mprotect((void *)((unsigned int)p&~(0x1000-1)),1,PROT_WRITE |  PROT_READ | PROT_EXEC );
	if( ret )
	{
		return ret;
	}
	
	*p = *pbak;
	
	ret = mprotect((void *)((unsigned int)p&~(0x1000-1)),1, PROT_READ | PROT_EXEC );
	if( ret )
	{
		return ret;
	}
	
	return 0;
}

